import { Jimp } from "jimp";
import { bimInterface, convertBimFont, countItem } from "./bimFontConvert";
import decodeUuid, { processOptions } from "./configUtil"
import { cpFile, dirExists, dwFileUrl, readTextForUrl, readUrlJson, saveAudioFile, saveImgToTextureAssets, saveUrlToFile, writeTxtToPath } from "./dir";
import { createDirIfNotExists } from "./dirtool";
import { GenerImgUUidMeat, getUuidForPath, replcaeUUid, resizeImgSize, spiltImg, stripImgUUid } from "./imgTool";
import { readJson } from "./util"
const path = require('path');
const axios = require('axios');
import { v4 as uuidv4 } from 'uuid';

const extnames = ['.png', '.jpg', '.jpeg', '.bmp', '.webp', '.pvr', '.pkm', '.astc'];//从引擎里面扣出来的 texture格式
export interface outPutSpine {
    isJson: boolean//是否为json格式
    spineName: string//spine的名称

    binUUid?: string//二进制文件的uuid json和bin只可能存在一个
    jsonUUid?: string//json文件的uuid json和bin只可能存在一个

    imgUUid: string//img格式的uuid
    alastText: string //alstext的uuid
    jsonText?: string//json字符串
    realPath: string//真实的资源id 原本在路劲里的
}
export interface outPutAudio {
    audioName: string,
    extName: string,

    uuid: string
    realPath: string//真实的资源id 原本在路劲里的

}

export class decodeAssets {
    nativeMd5Kv: {
        [key: string]: string
    } = {

        }
    importMd5Kv: {
        [key: string]: string
    } = {

        }
    bundleName = "game"
    configJson = "./src/input/game/config.json"
    outDir = "./outPut"
    bundleUrl: string = "https://wbgame-demo.jiligames.com/fullhouse3/assets/game/"
    baseBundleUrl: string = "https://wbgame-demo.jiligames.com/fullhouse3/assets"
    // bundleUrl: string = "https://wbgame-demo.jiligames.com/fish15/assets/game"

    isCompression = false

    configJsonObj: any = null
    outJsonObj: any = null
    configJsonFileMd5: string = "54be2"



    //md5缓存
    md5CatchKv: { [key: string]: any[] } = {}
    importObjCatchKv: { [key: string]: any } = {}
    jumpKv: { [key: string]: string } = {}

    public async run() {
        await this.readConfig()
        
        await this.revertSpine()
        // await this.revertAudio()
        // await this.revertImg()
        // await this.reverBitmapFont()
        // await this.reverParticleAsset()
        // await this.reverFont()
        // await this.reverScene()
        // await this.reverFont()
        // await this.revertPrefab()
        // await this.revertJumpAssets()
        return this

    }

    async readConfig() {
        // readUrlJson()
        let u = `${this.bundleUrl}/config.${this.configJsonFileMd5}.json`
        console.warn("config url", u)
        let configJson = await readUrlJson(u)
        //@ts-ignore
        if (configJson.err) return
        //@ts-ignore
        let configJsonObj = this.configJsonObj = configJson.data

        let pro = this.outJsonObj = processOptions(JSON.parse(JSON.stringify(configJsonObj)))
        //@ts-ignore
        let versions = configJsonObj.versions
        for (let i = 0; i < versions.import.length; i += 2) {
            let item = versions.import[i]
            let itemMd5 = versions.import[i + 1]
            this.importMd5Kv[item] = itemMd5
        }
        for (let i = 0; i < versions.native.length; i += 2) {
            let item = versions.native[i]
            let itemMd5 = versions.native[i + 1]
            this.nativeMd5Kv[item] = itemMd5

        }
        let rd: string[] = configJsonObj.redirect
        // redirect
        for (let i = 0; i < rd.length; i += 2) {
            let index = rd[i]
            let value = rd[i + 1]
            this.jumpKv[index] = value
        }
        await this.getImportJsons()
        //  console.warn("xxx===",this.jumpKv)
    }
    async revertJumpAssets() {
        //@ts-ignore
        let configJsonObj = this.configJsonObj
        for (let i in this.jumpKv) {
            let item = this.jumpKv[i]
            if (item) {
                console.warn(i)
                console.warn(item)
                console.warn("his.nativeMd5Kv[item]==>", this.nativeMd5Kv[item])

            }
        }
    }
    async reverScene() { }
    async revertPrefab() {
        let pro = this.outJsonObj
        for (let i in pro.paths) {
            let item = pro.paths[i]
            if (item[1] == "cc.Prefab") {
                // console.warn(item)
                let index = this.searchUUidInPath(i)
                let pack = await this.searchIdInPack(index)
                if (pack) {
                    let outObj: any[] = [1]
                    let packObj = this.importObjCatchKv[pack.fileName]
                    outObj.push(JSON.parse(JSON.stringify(packObj[1])))
                    outObj.push(JSON.parse(JSON.stringify(packObj[2])))
                    outObj.push(JSON.parse(JSON.stringify(packObj[3])))
                    outObj.push(JSON.parse(JSON.stringify(packObj[4])))

                    let preConfig: [] = packObj[5][pack.index]
                    for (let i = 0; i < preConfig.length; i++) {
                        let preItem = preConfig[i]
                        outObj.push(JSON.parse(JSON.stringify(preItem)))

                    }
                    console.warn(item)
                    // outDir
                    // console.warn(1111,packObj[5][pack.index])
                    let preObj = JSON.parse(JSON.stringify(outObj))
                    let s: string = item[0]
                    let lastIndex = s.lastIndexOf("\/")
                    s = s.slice(0, lastIndex)
                    await dirExists(`${this.outDir}/${this.bundleName}/pre/${s}`)
                    let task = await writeTxtToPath(JSON.stringify(preObj, null, 1), `${this.outDir}/${this.bundleName}/pre/${item[0]}.pre.txt`)
                }

            }
        }
    }
    async reverFont() {
        return
        // 0: "cc.Prefab"
        // 1: "cc.ImageAsset"
        // 2: "cc.Texture2D"
        // 3: "cc.SpriteFrame"
        // 4:"cc.BufferAsset"
        // 5: "cc.SpriteAtlas"
        // 6: "cc.ParticleAsset"
        // 7: "cc.BitmapFont"
        // 8: "cc.TextAsset"
        // 9: "cc.AnimationClip"
        // 10: "cc.AudioClip"
        // 11: "cc.Asset"
        // 12:"sp.SkeletonData"
        let pro = this.outJsonObj
        for (let i in pro.paths) {
            let item = pro.paths[i]
            if (item[1] == "cc.TextAsset") {
                console.warn(item)
            }
        }
    }
    async reverParticleAsset() {
        // 'cc.ParticleAsset',
        let pro = this.outJsonObj
        for (let i in pro.paths) {
            let item = pro.paths[i]
            if (item[1] == "cc.ParticleAsset") {
                console.warn("item",item)
                let uuidIndex = this.searchUUidInPath(i)
                let pack = await this.searchIdInPack(uuidIndex)
                // console.warn(item)
                // console.warn(pack)
                let md5 = this.nativeMd5Kv[uuidIndex]
                // console.warn("md5",md5)
                // console.warn(i)
                let url = `${this.bundleUrl}/native/${i[0]}${i[1]}/${i}.${md5}.plist`
                // console.warn(url)
                if (pack) {
                    let particData = this.importObjCatchKv[pack.fileName][5][pack.index]
                    let particName = particData[0][0][1]
                    let spiltText = await readTextForUrl(url)
                    console.warn(particName)
                    //@ts-ignore
                    if (!spiltText.err) {
                        let m: string = item[0]
                        let lastIndex = m.lastIndexOf("/")
                        m = m.slice(0, lastIndex + 1)
                        let outSpfUrl = `${this.outDir}/${this.bundleName}/outSpf/${m}`
                        await dirExists(outSpfUrl)
                        let outPath = `${outSpfUrl}${particName}.plist`
                        //@ts-ignore
                        await writeTxtToPath(spiltText.data, outPath)
                        //@ts-ignore
                        let d: string = spiltText.data
                        let imgUUid = stripImgUUid(d)
                        if (imgUUid) {

                            let data = await this.genParticleImgUUid(imgUUid, `${outSpfUrl}${particName}`)
                            if (data) {
                                //@ts-ignore
                                let txt = replcaeUUid(spiltText.data, data[1])
                                await writeTxtToPath(txt, outPath)
                            }
                        }
                    }else{
                        console.warn("sss===")
                    }

                }else{
                    console.warn("notinpack",item)
                }

            }
        }
    }

    async genParticleImgUUid(uuid: string, outPath: string) {
        let uuidIndex = this.searchUUidInPath(uuid)
        let pack = await this.searchIdInPack(uuidIndex)
        if (pack) {
            let imgData = this.importObjCatchKv[pack.fileName][5][pack.index]
            let packIndex = imgData[5][0]
            let uuid = this.importObjCatchKv[pack.fileName][1][packIndex]
            uuid = decodeUuid(uuid).split("@")[0]
            let imgIndex = this.searchUUidInPath(uuid)
            let md5 = this.nativeMd5Kv[imgIndex]
            let imgPack = await this.searchIdInPack(imgIndex)
            if (imgPack) {
                // console.warn(url)

                let imgPackObj = this.importObjCatchKv[imgPack.fileName][5][imgPack.index]
                // console.warn("imgPackObj====>",imgPackObj[0][0].fmt)
                let fmt: string[] = imgPackObj[0][0]?.fmt?.split("_")[0] ?? 0
                //@ts-ignore
                let extName = extnames[fmt]
                let url = `${this.bundleUrl}/native/${uuid[0]}${uuid[1]}/${uuid}.${md5}${extName}`
                let outFilePath = `${this.outDir}/temp/${uuid}${extName}`
                await dirExists(`${this.outDir}/temp/`)
                await saveImgToTextureAssets(url, outFilePath)
                let outDir = outPath.slice(0, outPath.lastIndexOf("/") + 1)
                // console.warn(outDir)
                await dirExists(outDir)
                let spedImg = await spiltImg(outFilePath, `${outPath}`, imgData[0][0], extName)
                let uuids = getUuidForPath(spedImg, 2)
                let uid1 = uuids[0]
                let uid2 = uuids[1]
                let metaTxt = GenerImgUUidMeat(uid1, uid2, imgData[0][0])
                await writeTxtToPath(metaTxt, `${spedImg}.meta`)
                return [uid1, uid2]
            }

        }
        // console.warn(pack)
        // let uuids:string[] = this.configJsonObj.uuids
        // let index = uuids.indexOf(uuid)
        // console.warn(index,uuid)
    }
    async reverBitmapFont() {
        let pro = this.outJsonObj
        for (let i in pro.paths) {
            let item = pro.paths[i]
            if (item[1] == "cc.BitmapFont") {
                let uuidIndex = this.searchUUidInPath(i)
                let pack = await this.searchIdInPack(uuidIndex)
                // console.warn("index===>",pack)
                if (pack) {

                    let importObj = this.importObjCatchKv[pack.fileName]
                    let fontConfig: bimInterface = {
                        fontName: "",
                        extName: "",
                        lineHeight: "",
                        fontSize: "",
                        originalSizeW: "",
                        originalSizeH: "",
                        countList: [],
                        base: ""
                    }
                    let config = importObj[5][pack.index][0][0]
                    let fontName = config[1]


                    let alastName: string = config[3].atlasName
                    let spAlastName = alastName.split(".")
                    let alastNameExname = `.${spAlastName[spAlastName.length - 1]}`


                    let sourceImgUUid = importObj[1][importObj[5][pack.index][5][0]]
                    let sUUid = sourceImgUUid
                    sourceImgUUid = decodeUuid(sourceImgUUid)

                    fontConfig.fontName = fontName
                    fontConfig.extName = alastNameExname
                    fontConfig.fontSize = config[3].fontSize
                    fontConfig.lineHeight = config[3].commonHeight
                    fontConfig.base = config[3].commonHeight

                    let imgUUidIndex = this.searchUUidInPath(sourceImgUUid)
                    let imgPack = await this.searchIdInPack(imgUUidIndex)
                    let img = this.importObjCatchKv[imgPack.fileName][5][imgPack.index]
                    //源img
                    if (imgPack) {
                        let originalSize = img[0][0].originalSize
                        fontConfig.originalSizeW = originalSize.width
                        fontConfig.originalSizeH = originalSize.height
                        // if(originalSize.width == 1024 && originalSize.height == 512){
                        // console.warn(img[0][0].rect.width)
                        // console.warn("ccc------")
                        // return
                        // }
                        fontConfig.originalSizeW = img[0][0].rect.width
                        fontConfig.originalSizeH = img[0][0].rect.height
                    }

                    let fontDefDictionary = config[3].fontDefDictionary
                    for (let i in fontDefDictionary) {
                        let item = fontDefDictionary[i]
                        let countItem: countItem = {
                            id: "",
                            x: "",
                            y: "",
                            width: "",
                            height: "",
                            xoffset: "",
                            yoffset: "",
                            xadvance: ""
                        }
                        countItem.xadvance = item.xAdvance
                        countItem.yoffset = item.yOffset
                        countItem.xoffset = item.xOffset
                        countItem.id = i
                        countItem.x = item.rect.x
                        countItem.y = item.rect.y
                        countItem.width = item.rect.width
                        countItem.height = item.rect.height
                        fontConfig.countList.push(countItem)
                    }
                    let bimText = convertBimFont(fontConfig)
                    let uid = this.searchUUidInPath(sourceImgUUid.split("@")[0])
                    // console.warn("sourceImgUUid.split[0]",sourceImgUUid.split("@")[0])

                    // console.warn(sUUid)


                    let outSpfUrl = `${this.outDir}/${this.bundleName}/outSpf/${item[0]}`
                    // console.warn(outSpfUrl)
                    let lastIndex = outSpfUrl.lastIndexOf("/")
                    // console.warn('last',outSpfUrl.slice(0,lastIndex+1))
                    let fontPath = outSpfUrl.slice(0, lastIndex + 1)
                    await dirExists(fontPath)
                    await writeTxtToPath(bimText, `${outSpfUrl}.fnt`)

                    let sourceImgUUidIndex = this.searchPathIndex(item[0] + "\/spriteFrame")
                    let spfInPack = await this.searchIdInPack(sourceImgUUidIndex)
                    if (spfInPack) {

                        // console.warn("spfInPack",spfInPack)
                        // console.warn(sourceImgUUidIndex)
                        let sourceSpf = this.importObjCatchKv[spfInPack.fileName][5][spfInPack.index]

                        let realSourceImgUUid: string = this.importObjCatchKv[spfInPack.fileName][1][sourceSpf[5][0]]
                        realSourceImgUUid = realSourceImgUUid.split("@")[0]
                        realSourceImgUUid = decodeUuid(realSourceImgUUid)
                        // spiltImg()
                        let index = this.searchUUidInPath(realSourceImgUUid)
                        // console.warn("realSourceImgUUid==>",realSourceImgUUid)
                        // console.warn("md5==>",this.nativeMd5Kv[index])
                        let realSourceMd5 = this.nativeMd5Kv[index]
                        let url = `${this.bundleUrl}/native/${realSourceImgUUid[0]}${realSourceImgUUid[1]}/${realSourceImgUUid}.${realSourceMd5}${alastNameExname}`

                        let outFilePath = `${this.outDir}/temp/${realSourceImgUUid.split("@")[0]}.${realSourceMd5}${alastNameExname}`
                        // console.warn("uri地址",url)
                        // let outPath = outSpfUrl+".png"
                        // console.warn("裁剪对应图片", outSpfUrl+".png")
                        // console.warn("源地址",outFilePath)
                        await dirExists(`${this.outDir}/temp/`)
                        let saveTask = await saveImgToTextureAssets(url, outFilePath)
                        //@ts-ignore
                        if (!saveTask.err) {


                            let cropObj = {
                                rotated: <boolean>false,
                                rect: {
                                    x: 0,
                                    y: 0,
                                    width: 0,
                                    height: 0
                                }
                                ,
                                name: fontName
                            }
                            cropObj.rotated = sourceSpf[0][0].rotated
                            cropObj.rect.x = sourceSpf[0][0].rect.x
                            cropObj.rect.y = sourceSpf[0][0].rect.y
                            cropObj.rect.width = Number(fontConfig.originalSizeW)
                            cropObj.rect.height = Number(fontConfig.originalSizeH)
                            let m = outSpfUrl.slice(0, outSpfUrl.lastIndexOf("/") + 1)
                            await dirExists(m)
                            // // console.warn("xsx",m)
                            // // console.warn("outSpfUrl===>",outSpfUrl)
                            // console.warn("outFilePath===>",outFilePath)
                            // console.warn("outSpfUrl===>",outSpfUrl)
                            // console.warn("cropObj===》",cropObj)
                            cropObj.rect.width = sourceSpf[0][0].rect.width
                            cropObj.rect.height = sourceSpf[0][0].rect.height
                            await spiltImg(outFilePath, outSpfUrl, cropObj, ".png", {
                                h: Number(fontConfig.originalSizeH),
                                w: Number(fontConfig.originalSizeW)
                            })
                            // await spiltImg(outFilePath,outSpfUrl,cropObj,".png")


                            // break
                            // console.warn("outPath===>",outFilePath)
                            // console.warn("outPath1===>",outSpfUrl)
                            // console.warn("cropObj===>",cropObj)
                            // console.warn("sourceSpf===>",sourceSpf[0][0])
                            // console.warn("sourceSpf1===>",sourceSpf[0][0].rotated)

                        }
                        // let outSpfUrlReal = `${this.outDir}/${this.bundleName}/outSpf/`

                        // let rg = /\/spriteFrame/
                        // let m = outSpfUrlReal.replace(rg, "")
                        // let lastIndexreal = m.lastIndexOf("/")
                        // m = m.slice(0, lastIndexreal + 1)

                        // await dirExists(m)
                        // await spiltImg(outSpfUrlReal, `${outSpfUrl}`, spfData[0][0], extName)



                        // console.warn("item====>",this.searchPathIndex(item[0]+"\/spriteFrame"))
                        //@ts-ignore
                        // await resizeImgSize(`${outSpfUrl}.png`,fontConfig.originalSizeW,fontConfig.originalSizeH)
                        // console.warn("sss=====>",`${outSpfUrl}.png`)

                    }

                }
            }
        }
    }
    async revertSpine() {
        let pro = this.outJsonObj

        for (let i in pro.paths) {
            let item = pro.paths[i]
            if (item[1] == "sp.SkeletonData") {
                let indexUUid = this.searchUUidInPath(i)
                let pack = await this.searchIdInPack(indexUUid)
                if (pack) {
                    let f = this.importObjCatchKv[pack.fileName]
                    //@ts-ignore
                    let skelConfig = f["5"][pack.index]
                    //@ts-ignore
                    let skeImportImgUidIndex = skelConfig[5]
                    //@ts-ignore
                    let imgUid = f[1][skeImportImgUidIndex]
                    let filePath = item[0]

                    let spineName = skelConfig[0][0][1]//spine本名
                    let spineExtName = skelConfig[0][0][2]//后缀名字 变回去的时候要成skel
                    let alstsText = skelConfig[0][0][3]//图集的文本
                    let isJson = spineExtName != ".bin"
                    if (isJson) {
                        let alstsText = skelConfig[0][0][2]
                        let jsonText = JSON.stringify(skelConfig[0][0][4])
                        if (!imgUid) {
                            //TODO一个图集引用多个的情况
                            // console.warn("333344",skelConfig[5][0])
                            // return
                            imgUid = f[1][skelConfig[5][0]]
                            // console.warn("imgUid===>",imgUid)
                        }
                        await this.outPutSpine({
                            imgUUid: imgUid,
                            spineName: spineName,
                            alastText: alstsText,
                            realPath: filePath,
                            binUUid: i,
                            isJson: isJson,
                            jsonText: jsonText
                        })


                    } else {
                        await this.outPutSpine({
                            imgUUid: imgUid,
                            spineName: spineName,
                            alastText: alstsText,
                            realPath: filePath,
                            binUUid: i,
                            isJson: isJson,

                        })
                    }

                }
                continue
            }
        }
    }
    async revertImg() {
        // await this.cpAlasts()
        let pro = this.outJsonObj
        for (let i in pro.paths) {
            let item = pro.paths[i]
            let spfPath: string = item[0]
            if (item[1] == "cc.SpriteFrame") {
                console.warn("split sprie alast")
                let uuidIndex = await this.searchUUidInPath(i)
                let pack = await this.searchIdInPack(uuidIndex)
                if (pack) {
                    let f = this.importObjCatchKv[pack.fileName]
                    //@ts-ignore
                    let spfData = f[5][pack.index]
                    //@ts-ignore
                    let sourceUUidIndex = spfData[5][0]
                    //@ts-ignore
                    let s = decodeUuid(f[1][sourceUUidIndex])
                    // console.warn(s)
                    //@ts-ignore
                    // console.warn(s.split("@")[0])
                    let sourceInUuidIndex = this.searchUUidInPath(s.split("@")[0])
                    let inPack = await this.searchIdInPack(sourceInUuidIndex)
                    // console.warn(sourceInUuidIndex)
                    // console.warn(this.searchIdInPack(sourceInUuidIndex))
                    if (inPack) {
                        //@ts-ignore
                        let imgData = f[5][inPack.index]
                        let extName = extnames[imgData[0][0]?.fmt?.split("_")[0] ?? 0]

                        let md5 = this.nativeMd5Kv[sourceInUuidIndex]
                        let url = `${this.bundleUrl}/native/${s[0]}${s[1]}/${s.split("@")[0]}.${md5}${extName}`
                        let tempUrl = `${this.outDir}/temp/`
                        let outFilePath = `${this.outDir}/temp/${s.split("@")[0]}.${md5}${extName}`
                        await dirExists(tempUrl)
                        console.warn(url)
                        let saveTask = await saveImgToTextureAssets(url, outFilePath)
                        //@ts-ignore
                        if (saveTask && saveTask.err) {
                            ///@ts-ignore
                            console.warn("errpr", saveTask.err)
                        } else {

                            let outSpfUrl = `${this.outDir}/${this.bundleName}/outSpf/${spfPath}`

                            let rg = /\/spriteFrame/
                            let m = outSpfUrl.replace(rg, "")
                            let lastIndex = m.lastIndexOf("/")
                            m = m.slice(0, lastIndex + 1)

                            await dirExists(m)
                            await spiltImg(outFilePath, `${outSpfUrl}`, spfData[0][0], extName)

                        }
                    } else {
                        // console.warn("notpack=====》", f[1][sourceUUidIndex])
                        // console.warn("s====>",sourceUUidIndex)
                        let id = this.searchUUidInPath(s)
                        // if(s == "1d22e6da2@6c48a"){
                        //     console.warn("sxsdadda====")
                        // }else{
                        //     continue
                        // }
                        // console.warn("this",item)
                        // let md5 = this.nativeMd5Kv[i]
                        // console.warn("sourceUUidIndex",id,i)
                        // console.warn(md5)
                        // console.warn("this.jumpKv[id]===>",this.jumpKv[id])
                        // let configJsonObj = this.configJsonObj
                        // console.warn(configJsonObj.uuids[id])
                        console.warn("this.jumpKv[id]", this.jumpKv[id])
                        //@ts-ignore
                        if (this.jumpKv[id] == 1) {
                            console.warn("jump1===", item, s)
                            let f = await readJson("./src/input/game/setting.json")
                            //@ts-ignore
                            let configJsonMd5 = f.assets.bundleVers["main"]

                            let task = new decodeAssets()
                            task.baseBundleUrl = this.baseBundleUrl
                            task.bundleName = "main"
                            task.configJsonFileMd5 = configJsonMd5
                            task.bundleUrl = `${this.baseBundleUrl}/main/`
                            await task.readConfig()
                            let index = this.searchUUidInPath(i)
                            let pack = await this.searchIdInPack(index)

                            if (pack) {


                                console.warn("7787877777", i, pack)
                                console.warn(index)
                                console.warn(pack)
                                let spfImg = this.importObjCatchKv[pack.fileName][5][pack.index]
                                // console.warn(spfImg)
                                console.warn("跳到main包里找图")
                                s = s.split("@")[0]

                                let source = task.searchUUidInPath(s)
                                let taskPack = await task.searchIdInPack(source)

                                // let sourceImgObj = task.importObjCatchKv[taskPack.fileName][5][taskPack.index]
                                // console.warn("taskPack",sourceImgObj)
                                console.warn(44455, s)
                                // //@ts-ignore
                                // let obj = window["xx"] ?? {}
                                // //@ts-ignore
                                // window["xx"] = obj
                                let sourceMd5 = task.nativeMd5Kv[source]
                                // let sourceUrl  = `${task.bundleUrl}/native/${s[0]}${s[1]}/${s}.${sourceMd5}.png`
                                // console.warn(sourceUrl)
                                // console.warn(taskPack)
                                console.warn("spfImg===>", spfImg[0][0])
                                //    let sourceIndex =  task.searchUUidInPath(sourceUUid)
                                let sourceUUid = s
                                // let url = `${task.bundleUrl}/native/${sourceUUid[0]}${sourceUUid[1]}/${sourceUUid}.${sourceMd5}.png`
                                let url = `${task.bundleUrl}/native/${s[0]}${s[1]}/${s}.${sourceMd5}.png`
                                let tempUrl = `${this.outDir}/temp/`
                                console.warn("sssaasd==", url)

                                let outFilePath = `${this.outDir}/temp/${sourceUUid}.${sourceMd5}.png`
                                await dirExists(tempUrl)
                                // console.warn(url)
                                let saveTask = await saveImgToTextureAssets(url, outFilePath)
                                //@ts-ignore
                                if (!saveTask.err) {

                                    let outSpfUrl = `${this.outDir}/${task.bundleName}/outSpf/${spfPath}`
                                    let rg = /\/spriteFrame/
                                    let m = outSpfUrl.replace(rg, "")
                                    let lastIndex = m.lastIndexOf("/")
                                    m = m.slice(0, lastIndex + 1)
                                    await dirExists(m)
                                    await spiltImg(outFilePath, `${outSpfUrl}`, spfImg[0][0], ".png")

                                    // console.warn(url)
                                    // console.warn("sourceImg",sourceImg)
                                    // console.warn("sourceUUid====>",sourceUUid)
                                }
                            }

                        } else
                            //@ts-ignore
                            if (this.jumpKv[id] == 3) {
                                console.warn("item===>", item, s)
                            }



                        // console.warn(md5)
                        // let u = `${this.bundleUrl}/native/${s[0]}${s[1]}/${s.split("@")[0]}.${md5}.png`
                        // console.warn(u)


                    }

                } else {
                    console.warn(item)
                }

                // console.warn("pack",pack)
            }
            if(item[1] == "cc.ImageAsset"){
                
                let uuidIndex = await this.searchUUidInPath(i)
                console.warn(uuidIndex)
                let md5 = this.nativeMd5Kv[uuidIndex]
                
                let url = `${this.bundleUrl}/native/${i[0]}${i[1]}/${i}.${md5}`
               
               let spPath = spfPath
                let outSpfUrl = `${this.outDir}/${this.bundleName}/${spfPath}`

                let rg = /\/spriteFrame/
                let m = outSpfUrl.replace(rg, "")
                let lastIndex = m.lastIndexOf("/")
                m = m.slice(0, lastIndex + 1)
                console.warn("url===>",url)
                console.warn("outSpfUrl===>",outSpfUrl)
                await dirExists(m)
                try{
                    let extNames = extnames;
                    for(let ti  in extNames){
                        let extName = extNames[ti]
                        console.warn("purl===>",url+extName)
                        let saveTask = await saveImgToTextureAssets(url+extName, `${outSpfUrl}`+extName,false)
                        //@ts-ignore
                        if(!saveTask.err){
                            
                     
                        }
                    }
                }catch{

                }

                // console.warn("   this.bundleUrl",   this.bundleUrl)
                
            }
        }
    }
    /**
     * 搜索uuid 在跳转中的
     */
    searchIdInJump() { }
    // async cpAlasts() {
    //     return
    //     let pathName = `${this.importDir}`

    //     for(let i in this.outJsonObj.paths){
    //         let item = this.outJsonObj.paths[i]
    //         this.md5CatchKv[i] = item
    //     }
    //     // console.warn(this.md5CatchKv)
    //     // return
    //     for (let i in this.outJsonObj.packs) {
    //         let PackItem = `${pathName}/${i[0]}${i[1]}/${i}.json`
    //         console.warn(PackItem)
    //         let f = await readJson(PackItem)
    //         //@ts-ignore
    //         for(let i in f[1]){
    //             //@ts-ignore
    //             // console.warn( decodeUuid(f[1][i]))
    //             let decodeUUid = decodeUuid(f[1][i])
    //             // decodeUUid = decodeUUid.split("@")[0]
    //             let FileItem = this.md5CatchKv[decodeUUid]
    //             if (FileItem) {
    //                 console.warn(FileItem[1])
    //                 console.warn(FileItem)
    //                 console.warn("decodeUUid", decodeUUid)
    //             }
    //         }
    //         return

    //     }
    //     // console.warn(this.searchUUidInPath("ce56b9ac-6e9b-4e01-8bbc-4437715b507e"))
    // }
    async revertAudio() {
        let pro = this.outJsonObj
        let index = 0
        for (let i in pro.paths) {
            let item = pro.paths[i]
            if (item[1] == "cc.AudioClip") {
                let indexUUid = this.searchUUidInPath(i)
                let pack = await this.searchIdInPack(indexUUid)
                if (pack) {

                    // let pathName = `${this.importDir}/${pack.fileName[0]}${pack.fileName[1]}/${pack.fileName}`
                    let f = this.importObjCatchKv[pack.fileName]
                    //@ts-ignore
                    let audioData = f[5][pack.index][0][0]

                    ///////////////
                    let audioName = audioData[1]
                    let extName = audioData[2]
                    let path = item[0]
                    let md5 = this.nativeMd5Kv[indexUUid]

                    let url = `${this.bundleUrl}/native/${i[0]}${i[1]}/${i}.${md5}${extName}`
                    console.warn(url)

                    let p = `${this.outDir}/${this.bundleName}/${path}`
                    let lastIndex = p.lastIndexOf("/")
                    let m = p.slice(0, lastIndex + 1)

                    // pp.slice(0,lastIndex+1)
                    await dirExists(`${m}`)//创建spine的目录
                    await saveAudioFile(url, `${p}${extName}`)


                    // await this.outPutAudioHandel({
                    //     audioName: audioName,
                    //     realPath: path,
                    //     extName: extName,
                    //     uuid: i
                    // })

                }

            }

            index += 1
        }
    }

    /**
     * 在打的包中搜索id
     * @param id
     * @returns
     */
    private async searchIdInPack(id: number | string) {
        for (let i in this.configJsonObj.packs) {
            let itemFileName = i
            let item = this.configJsonObj.packs[i]
            let index = item.indexOf(`${id}`)
            if (index != -1) {
                return {
                    fileName: itemFileName,
                    index: index
                }
            }

        }
        return null
    }
    /**
     * 调用这个函数直接导出spine
     * @param outData
     */
    async outPutSpine(outData: outPutSpine) {
        if (outData.isJson) {
            console.warn("输出spineJson格式")
            //TODO json格式的直接拷贝就行了
            await this.outPutSpineJsonHandel(outData)
        } else {
            await this.outPutSpineBinHandel(outData)
        }
    }
    /**
     * GameIntro.atlas
     * 导出二进制的spine
     * @param outData
     */
    async outPutSpineBinHandel(outData: outPutSpine) {
        let path = `${this.outDir}/${this.bundleName}/${outData.realPath}`
        await dirExists(`${path}`)//创建spine的目录
        await writeTxtToPath(outData.alastText, `${path}/${outData.spineName}.atlas`)

        let binUUidIndex = this.searchUUidInPath(outData.binUUid)
        let binMd5 = this.nativeMd5Kv[binUUidIndex]
        let urlPath = `${this.bundleUrl}/native/${outData.binUUid[0] + outData.binUUid[1]}/${outData.binUUid}.${binMd5}.bin`
        let rsp = await saveUrlToFile(urlPath, `${path}/${outData.spineName}.skel`)



        let imgRealUuid = outData.imgUUid.split("@")[0]
        imgRealUuid = decodeUuid(imgRealUuid)
        let sp = outData.alastText.split("\n")
        for (let i of sp) {
            if (i) {
                let l = i.split(".")
                if (l.length > 1) {
                    let extName = "." + l[l.length - 1];
                    let imgUUidIndex = this.searchUUidInPath(imgRealUuid)
                    let imgUuIdMd5 = this.nativeMd5Kv[imgUUidIndex]
                    let imgUrl = `${this.bundleUrl}/native/${imgRealUuid[0]}${imgRealUuid[1]}/${imgRealUuid + "." + imgUuIdMd5 + extName}`
                    let newPath = `${path}/${outData.spineName}${extName}`
                    let cp = await saveUrlToFile(imgUrl, newPath)
                    //@ts-ignore
                    if (cp.err) {
                        // let uuid = this.searchUUidInPath(imgRealUuid)
                        // console.warn(uuid)
                        //@ts-ignore
                        // console.warn("cp",cp.err)
                    }
                }
                break
            }
        }

    }


    /**
    * 导出二进制的spine
    * @param outData
    */
    async outPutSpineJsonHandel(outData: outPutSpine) {
        // console.warn("outPutSpineJsonHandel===>", outData)

        let path = `${this.outDir}/${this.bundleName}/${outData.realPath}`
        await dirExists(`${path}`)//创建spine的目录
        await writeTxtToPath(outData.alastText, `${path}/${outData.spineName}.atlas`)
        await writeTxtToPath(outData.jsonText, `${path}/${outData.spineName}.json`)
        if (!outData.imgUUid) {
            console.warn("notImgUuid", outData)
            return
        }
        let imgRealUuid = outData.imgUUid.split("@")[0]
        imgRealUuid = decodeUuid(imgRealUuid)
        console.warn(imgRealUuid)



        let sp = outData.alastText.split("\n")
        for (let i of sp) {
            if (i) {
                let l = i.split(".")
                if (l.length > 1) {
                    let extName = "." + l[l.length - 1];
                    let imgUUidIndex = this.searchUUidInPath(imgRealUuid)
                    let imgUuIdMd5 = this.nativeMd5Kv[imgUUidIndex]
                    let imgUrl = `${this.bundleUrl}/native/${imgRealUuid[0]}${imgRealUuid[1]}/${imgRealUuid + "." + imgUuIdMd5 + extName}`
                    let newPath = `${path}/${outData.spineName}${extName}`
                    // console.warn(imgUrl)
                    // console.warn(newPath)
                    let cp = await saveUrlToFile(imgUrl, newPath)
                    //@ts-ignore
                    if (cp.err) {
                        // let uuid = this.searchUUidInPath(imgRealUuid)
                        // console.warn(uuid)
                        //@ts-ignore
                        // console.warn("cp",cp.err)
                    }
                }
                break
            }
        }
    }
    /**
     * 搜uuid 找路劲
     * @param uuid
     */
    searchUUidInPath(uuid: string) {
        let pro = this.configJsonObj
        let index = 0
        for (let i in pro.uuids) {
            if (decodeUuid(pro.uuids[i]) == uuid) {
                return i
            }
            index += 1
        }
        return -1
    }

    searchPathIndex(path: string) {
        let pro = this.configJsonObj
        for (let i in pro.paths) {
            let item = pro.paths[i]
            if (path == item[0]) {
                return i
            }
        }
        return -1
    }
    async getImportJsons() {
        for (let i in this.configJsonObj.packs) {
            let uuid = i
            let uuidIndex = this.searchUUidInPath(uuid)
            // console.warn(uuidIndex)
            // console.warn(this.importMd5Kv[uuidIndex])
            let md5 = this.importMd5Kv[uuidIndex]
            let url = `${this.bundleUrl}/import/${uuid[0]}${uuid[1]}/${uuid}.${md5}.json`
            console.warn(url)
            let data = await readUrlJson(url)
            //@ts-ignore
            this.importObjCatchKv[i] = data.data
        }

    }
}
(async () => {

    // https://uat-wbgame.jiligames.com/mc/assets/game/config.e43fe.json
        // let d = "https://wbgame-demo.jiligames.com/annin/3.6/web-mobile/assets/"

        // https://uat-wbgame.jiligames.com/fish15/assets/game/

        let d=  "https://uat-wbgame.jiligames.com/mc/assets/"
    let task = new decodeAssets()
    task.bundleName = "game"
    task.configJsonFileMd5 = "e43fe"
    task.bundleUrl = d + "game"
    task.outDir = "./s/"
    await task.run()
    return
    // let d = " https://uat-wbgame.jiligames.com/fullhouse3/assets/"
    // let task = new decodeAssets()
    // task.bundleName = "dc"
    // task.configJsonFileMd5 = "dc500"
    // task.bundleUrl = d + "game"
    // task.outDir = "./dc200/"
    // await task.run()
    // return
    //     let d = "https://uat-wbgame.jiligames.com/astarte2/3.6/web-mobile/assets/"
    // let task = new decodeAssets()
    // task.bundleName = "en"
    // task.configJsonFileMd5 = "40a40"
    // task.bundleUrl = d + "en"
    // await task.run()
    // return
    // let d = "https://uat-wbgame.jiligames.com/astarte2/3.6/web-mobile/assets/"
    // let task = new decodeAssets()
    // task.bundleName = "jili"
    // task.configJsonFileMd5 = "f13bd"
    // task.bundleUrl = d + "jili"
    // await task.run()

    let f = await readJson("./src/input/game/setting.json")
    // //@ts-ignore
    // console.warn(f.assets.bundleVers)
    let b = "https://wbgame-demo.jiligames.com/fullhouse3/assets"
    //@ts-ignore
    for (let i in f.assets.bundleVers) {

        //@ts-ignore
        let item = f.assets.bundleVers[i]
        // console.warn(`${b}/${i}/config.${item}.json`)
        let url = `${b}/${i}/config.${item}.json`
        // console.warn(url)
        let task = new decodeAssets()
        task.baseBundleUrl = "https://wbgame-demo.jiligames.com/fullhouse3/assets/"
        task.bundleName = i
        task.configJsonFileMd5 = item
        task.bundleUrl = `${b}/${i}/`
        await task.run()
    }
    return
    let w = await new decodeAssets().run()
    //     let uuidIndex = w.searchUUidInPath("be63f3db-2239-40f5-a583-516f2afa8ca2@f9941")
    //    //@ts-ignore
    //    let pack =  await  w.searchIdInPack(uuidIndex)
    //     console.warn(pack)
    // // console.warn(w.nativeMd5Kv)
    // let newKv: any = {}
    // for (let i in w.nativeMd5Kv) {
    //     newKv[w.nativeMd5Kv[i]] = i
    // }
    // console.warn(w.searchPathIndex("Sound/Effect/mp3/en/Rate5"))
})()
